<?php if (!defined('IN_SYS')) exit('Access Denied!');
/**
 * Db核心类文件只是实现了mysql模块
 *
 * @author Jerry
 */
class Db
{
	/**
     * @var  object
     */
    static private $_instance = null;
	
    /**
     * @var  string  最后一次执行的Sql
     */
    static private $_last_sql;
	
    /**
     * @var  resouse  MySql连接资源
     */
    static private $_link;
	
    /**
     * @var  boolean  是否开启sql调试
     */
    static public $debug = FALSE;
	
    /**
     * @var  int  最后执行插入操作的ID
     */
    static public $insert_id;
	
     /**
     * @var  string  query后的资源
     */
    static private $result;
	
    /**
     * @var  string  数据表
     */
    static private $_table;

    /**
	 * 当前的分页状态
	 * 数组内容说明：
	 * total : 总页数
	 * page  : 当前所在页号
	 * size  : 每页显示数量
	 * sum   : 总记录数
	 *
	 * @var array
	 */
	private $_pager = array('total' => 0, 'page' => 0, 'size' => 0, 'sum' => 0);

    /**
	 * 初始化
     *
	 */
    public static function Instance()
    {
        if ( null == self::$_instance ) {
			$class = __CLASS__;
			self::$_instance = new $class;
		}
		return self::$_instance;
    }

    /**
	 * 构造方法
     *
	 */
    private function __construct()
	{
		$_CONFIGS = Co::Config('sys');
        if (empty($_CONFIGS)) {
			throw new Exception('Can\'t connect to database, connection string is empty.');
		}
		$host = (string) $_CONFIGS['host'];
		$db_user = (string) $_CONFIGS['db_user'];
		$db_pass = (string) $_CONFIGS['db_pass'];
		$db_name = (string) $_CONFIGS['db_name'];
		
		self::$_link = mysql_connect($host, $db_user, $db_pass);

		if (mysql_errno()) throw new Exception("Connect failed " . mysql_error());

		mysql_select_db( $db_name, self::$_link );

        mysql_query( "SET NAMES UTF8;", self::$_link );
	}
	
	/**
	 * 设置一个数据表
     *
	 */
    public function setTable( $table )
    {
        self::$_table = $table;
        return self::$_instance;
    }

    /**
     * 执行SQL语句
     *
     * @param string $sql
     * @return Mysql_Result | mixed
     */
    public function Query( $sql )
    {
        if (self::$debug) {
           echo $sql;
        }
        if (($result = mysql_query($sql, self::$_link)) === FALSE) {
            throw new Exception( '[ '.$sql . ' ] -> ' .mysql_error());
        }
        // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query
        if (is_resource($result)) {
            self::$result = $result;
        }
        // Its an DELETE, INSERT, REPLACE, or UPDATE query
        elseif (is_bool($result)) {
            if(stripos($sql, 'INSERT') !== FALSE) {
                return self::$insert_id = mysql_insert_id(self::$_link);
            } else {
                return mysql_affected_rows(self::$_link);
            }
        }
        else {
            return null;
        }
    }
    
    public function fetchPage($sql = '', $pg = 1, $display = 20)
    {
        if (empty($sql)) return null;
		$current = intval($pg);
		$total = 0;
		if (preg_match("|GROUP\s*BY|ims", $sql) > 0)
		{
			$total = $this->num_rows($this->query($sql));
		}
		else
		{
			$csql = preg_replace("|SELECT(.*)FROM(.*)|ims", 'SELECT COUNT(*) FROM $2', $sql);
			$total = $this->result_first($csql);
		}
		if ($total < 1)
		{
			return null;
		}
		$page  = ceil($total / $display);  // 总页数
		$current = $current > 1 ? $current : 1;
		$current = $current > $page ? $page : $current;

		$offset = $display * $current - $display;
		$sql .= ' LIMIT ' . $offset . ', ' . $display;
		$data = $this->fetch_all($sql);

		return array('total'        => $total,
                     'page'         => $page,
                     'current'      => $current,
					 'data'         =>$data);
    }

    public function fetchRow()
    {

    }

    public function fetchField()
    {

    }
    
    public function fetchArry($query, $result_type = MYSQL_ASSOC)
    {
		return mysql_fetch_array($query, $result_type);
	}

    public function fetchAll( $sql, $id = '' )
    {
		$arr = array();
		$query = $this->query($sql);
		while($data = $this->fetch_array($query)){
			$id ? $arr[$data[$id]] = $data : $arr[] = $data;
		}
		return $arr;
    }
    
    /**
     * 读取一条数据
     *
     * @param int $id
     * @param string $pk 主键
     * @param array $fields
     * @return array
     */
    public function fetchRowById( $id = 0, $pk = 'id', $fields = '' )
    {
        if (is_array($fields) && !empty($fields)) {
            $fields = '`' . implode('`, `',$fields) . '`';
            self::$_last_sql = 'SELECT ' .$fields. ' FROM `' .self::$_table. '` WHERE `' .$pk. '`=' .$id. ' LIMIT 1';
        } else {
            self::$_last_sql = 'SELECT * FROM `' .self::$_table. '` WHERE `' .$pk. '`=' .$id. ' LIMIT 1';
        }
        self::Query(self::$_last_sql);
        return mysql_fetch_array(self::$result, MYSQL_ASSOC);
    }
    
    public function Result($query, $row = 0)
    {
		return @mysql_result($query, $row);;
	}
	
	/**
	 * 插入操作
	 *
	 * @param array $fields 传入参数array('uid' => 1,'username'=>'Jerry');
	 * 						将执行 $sql = "INSERT INTO table (uid, username) VALUES (1, 'Jerry')"							
	 * 
	 * @return boolean
	 */
    public function Insert( array $fields )
    {
        if (is_array($fields) && !empty($fields)) {
            $table_fields = $table_value = array();
            foreach ($fields as $field=>$value) {
                $table_value[] = "'".$value."'";
                $table_fields[] = '`'.$field.'`';
            }
            self::$_last_sql = 'INSERT INTO ' .self::$_table .'('. implode(',', $table_fields). ') VALUES (' .implode(',', $table_value). ')';
            return self::Query(self::$_last_sql);
        }
        return FALSE;
    }

    /**
     * 删除表数据
     * 
     * @param array $conditions 条件数组 array('uid' => 1)
     * @param int $limit 要删除多少条数据
     * @return boolean
     */
    public function Delete( array $conditions , $limit = 1)
    {
        if (is_array($conditions) && !empty($conditions)) {
            self::$_last_sql = 'DELETE FROM `' .self::$_table. '` WHERE ';
             foreach ($conditions as $field=>$value) {
                self::$_last_sql .= '`' .$field. "`='" .$value. "' AND ";
            }
            self::$_last_sql = substr(trim(self::$_last_sql), 0, -3);
        } else {
            self::$_last_sql = 'DELETE FROM `' .self::$_table;
        }
        self::$_last_sql = !$limit ? self::$_last_sql : self::$_last_sql  .' LIMIT '. intval($limit);
        return self::Query(self::$_last_sql);
    }

    /**
	 * 取得上查询的分页数据
	 *
	 * @return array
	 */
	public function Pager()
	{
		return self::$_pager;
	}
	
	/**
	 * 更新数据
	 *
	 * @param array $fields 要修改的字段 array('username' => 'Jerry')
	 * 
	 * @param mixed $conditions 
	 * @return unknown
	 */
    public function Update(array $fields, array $conditions, $limit = 1)
	{
		if (is_array($fields) && !empty($fields)) {
			self::$_last_sql = 'UPDATE `' .self::$_table .'` SET ';	
            $table_fields = $table_value = array();
            // 字段
            foreach ($fields as $field=>$value) {
            	self::$_last_sql .= '`'. $field .'`=`'. $value.'`';
            }
            
            // 条件
            if (is_array($conditions) && !empty($conditions)) {
	            foreach ($conditions as $condition=>$condition_value) {
	            	self::$_last_sql .= ' WHERE `'. $condition .'`=`'. $condition_value.'`';
	            }
            }
            self::$_last_sql = !$limit ? self::$_last_sql : self::$_last_sql  .' LIMIT '. intval($limit);
        	return self::Query(self::$_last_sql);
        }
		return FALSE;
	}
	
	/**
	 * 释放连接
	 *
	 * @return boolean
	 */
    public function Close()
    {
		if (is_resource(self::$_link))
		{
			@mysql_close(self::$_link);
		}
		// 释放连接
        self::$_link = null;
        // 释放数据库实例
		self::$_instance = null;
		
		return TRUE;
	}

    public function __destruct()
	{
        self::Close();
	}
}
?>